#! /bin/sh -eu
#
# Copyright 2008--2010 Mattias Norrby
#
# This file is part of Test Dept..
#
# Test Dept. is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Test Dept. is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Test Dept..  If not, see <http://www.gnu.org/licenses/>.

TEST_MAINS="${*:-}"
ERROR_LOG="/tmp/test_dept$$.log"

trap cleanup 2 4 6

cleanup() {
    EXITCODE="${1:-2}"
    rm -f $ERROR_LOG
    exit $EXITCODE
}

run_test() {
  SUITE="$1"
  TEST="$2"
  echo "+++ ${SUITE}, ${TEST}: " >&2
  NUMBER_OF_TESTS="`expr ${NUMBER_OF_TESTS:-0} + 1`"
  if $SUITE $TEST; then
    printf "."
    echo "---" >&2
  else
    [ "$?" -gt 128 ] && echo "Failure: Aborted on signal" >&2
    NUMBER_OF_ERRORS="`expr ${NUMBER_OF_ERRORS:-0} + 1`"
    printf "F"
    echo "-- " >&2
  fi
}

if rm -f $ERROR_LOG; then
  touch $ERROR_LOG
else
  echo "Could not write to log file (${ERROR_LOG}). Exiting."
  exit 2;
fi

for suite in $TEST_MAINS; do
  suite="`dirname $suite`/`basename $suite`" 
  for test in `$suite`; do
    run_test "$suite" "$test" 2>>$ERROR_LOG
  done
done
echo

if [ "${NUMBER_OF_ERRORS:-0}" -gt "0" ]; then
  echo "Failures: ${NUMBER_OF_ERRORS:-0} (of ${NUMBER_OF_TESTS:-0} run tests):"
  sed -n '/^-- $/{H; g; p; }; H; /^+++/h' $ERROR_LOG
  cleanup 1
fi

cleanup 0
